<?php
/**
 * Created by PhpStorm.
 * User: zhuanggit
 * Date: 2020/11/11
 * Time: 11:14
 */
/**
 * 阿里云短信验证码发送类
 * @author Administrator
 *
 */
class Sms {
    // 保存错误信息
    public $error;
    // Access Key ID
    private $accessKeyId = '';
    // Access Access Key Secret
    private $accessKeySecret = '';
    // 签名
    private $signName = '';
    public function __construct($cofig = array()) {
        $cofig = array (
            'accessKeyId' => 'LTAIFHCtKrHfmlAb',
            'accessKeySecret' => 'JXhb2GMKkPZqRLjcobggVSD9PGlC9T',
        );
        // 配置参数
        $this->accessKeyId = $cofig ['accessKeyId'];
        $this->accessKeySecret = $cofig ['accessKeySecret'];
        $this->signName = $cofig ['signName'];
    }
    private function percentEncode($string) {
        $string = urlencode ( $string );
        $string = preg_replace ( '/\+/', '%20', $string );
        $string = preg_replace ( '/\*/', '%2A', $string );
        $string = preg_replace ( '/%7E/', '~', $string );
        return $string;
    }
    /**
     * 签名
     *
     * @param array $parameters
     * @param string $accessKeySecret
     * @return string
     */
    private function computeSignature($parameters, $accessKeySecret) {
        ksort ( $parameters );
        $canonicalizedQueryString = '';
        foreach ( $parameters as $key => $value ) {
            $canonicalizedQueryString .= '&' . $this->percentEncode ( $key ) . '=' . $this->percentEncode ( $value );
        }
        $stringToSign = 'GET&%2F&' . $this->percentencode ( substr ( $canonicalizedQueryString, 1 ) );
        $signature = base64_encode ( hash_hmac ( 'sha1', $stringToSign, $accessKeySecret . '&', true ) );
        return $signature;
    }
    /**
     * @param string $mobile
     * @param string $verify_code
     * @param string $template_code
     * @return string
     *
     */
    public function send_verify($mobile, $verify_code, $sign_name,$template_code) {
        $params = array (   //此处作了修改
            'SignName' => $sign_name,
            'Format' => 'JSON',
            'Version' => '2017-05-25',
            'AccessKeyId' => $this->accessKeyId,
            'SignatureVersion' => '1.0',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid (),
            'Timestamp' => gmdate ( 'Y-m-d\TH:i:s\Z' ),
            'Action' => 'SendSms',
            'TemplateCode' => $template_code,
            'PhoneNumbers' => $mobile,
            'TemplateParam' => '{"code":'.$verify_code.'}'   //更换为自己的实际模版
        );
        //var_dump($params);die;
        // 计算签名并把签名结果加入请求参数
        $params ['Signature'] = $this->computeSignature ( $params, $this->accessKeySecret );
        // 发送请求（此处作了修改）
        //$url = 'https://sms.aliyuncs.com/?' . http_build_query ( $params );
        $url = 'http://dysmsapi.aliyuncs.com/?' . http_build_query ( $params );

        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        $result = json_decode ( $result, true );
        //var_dump($result);die;
        if (isset ( $result ['Code'] )) {
            if ($result['Code']=='OK'){
                return true;
            }else{
                return $result['Message'];
            }
        }else{
            return '服务器出错';
        }
    }
}
////测试例子
//$mobile ='XXXXXXXXXXX';
//$code=rand(100000, 999999);
////发送短信
////短信模板id,验证码
//$sign_name='爱计时赛事平台';
//$tCode='SMS_205444478';
//$sms = new Sms();
////测试模式
//$result = $sms->send_verify($mobile, $code,$sign_name,$tCode);
//if ($result) {
//    die(json_encode(array('errno' => 0,'msg'=>'发送成功','code'=>$code)));
//} else {
//    die(json_encode(array('errno' => 1,'msg'=>$result,'code'=>$code)));
//}
